package com.xyazm.fulfill.event;

import com.xyazm.common.enums.OrderStatusChangeEnum;
import com.xyazm.common.utils.JsonUtil;
import com.xyazm.fulfill.domain.entity.OrderFulfillDO;
import com.xyazm.fulfill.domain.entity.OrderFulfillLogDO;
import com.xyazm.fulfill.domain.event.OrderEvent;
import com.xyazm.fulfill.domain.event.OrderSignedEvent;
import com.xyazm.fulfill.domain.param.TriggerOrderAfterFulfillEventParam;
import com.xyazm.fulfill.enums.OrderFulfillOperateTypeEnum;
import com.xyazm.fulfill.enums.OrderFulfillStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 订单已签收事件处理器
 * @author xuyou
 * @date 2023年02月14日 21:39
 */
@Slf4j
@Service
public class OrderSignedEventProcessor extends AbstractAfterFulfillEventProcessor {

    @Override
    protected boolean checkFulfillStatus(OrderFulfillDO orderFulfillDO) {
        if (!OrderFulfillStatusEnum.DELIVERY.getCode().equals(orderFulfillDO.getStatus())) {
            log.info("履约单无法配送！orderId={}", orderFulfillDO.getOrderId());
            return false;
        }
        return true;
    }

    @Override
    protected void doBizProcess(TriggerOrderAfterFulfillEventParam param, OrderFulfillDO orderFulfillDO) {
        // 将履约单状态改为 履约单签收
        OrderFulfillOperateTypeEnum operateType = OrderFulfillOperateTypeEnum.SIGN_ORDER;
        updateStatusAndSaveLog(orderFulfillDO, operateType);
    }

    @Override
    protected boolean orderNeedSendMsg(TriggerOrderAfterFulfillEventParam param) {
        String orderId = param.getOrderId();
        // 查询该订单下所有的履约单
        List<OrderFulfillDO> list = orderFulfillDAO.listByOrderId(orderId);
        List<OrderFulfillLogDO> logs = orderFulfillLogDAO.list(orderId, OrderFulfillStatusEnum.DELIVERY.getCode());
        // 只要日志数 >= 该订单下所有的履约单数，说明就是最后一笔履约单进行履约调度了
        return logs.size() >= list.size();
    }

    @Override
    protected String buildMsgBody(TriggerOrderAfterFulfillEventParam param) {
        String orderId = param.getOrderId();
        OrderSignedEvent orderSignedEvent = (OrderSignedEvent) param.getAfterFulfillEvent();
        orderSignedEvent.setOrderId(orderId);
        // 构建订单已签收消息体
        OrderEvent<OrderSignedEvent> orderEvent = buildOrderEvent(orderId, OrderStatusChangeEnum.ORDER_SIGNED,
                orderSignedEvent);
        return JsonUtil.object2Json(orderEvent);
    }
}
